<template>
  <el-dialog
    v-model="dialogVisible"
    title="角色权限关联"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div v-loading="loading" class="permission-content">
      <div class="role-info">
        <el-tag type="primary" size="large">
          当前角色: {{ roleName }}
        </el-tag>
      </div>
      
      <div class="permission-list">
        <h4>选择要关联的权限:</h4>
        <ElTreeComponent
          ref="treeRef"
          :data="menuTree"
          :props="treeProps"
          show-checkbox
          node-key="id"
          :default-checked-keys="selectedMenuIds"
          :check-strictly="false"
          class="menu-tree"
          @check="handleCheck"
        />
      </div>
      
      <div class="selected-count">
        已选择 {{ selectedCount }} 个权限
      </div>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">
          取消
        </el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          确认关联
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import type { ElTree } from 'element-plus';
import {
  ElButton,
  ElDialog,
  ElMessage,
  ElTag,
  ElTree as ElTreeComponent,
} from 'element-plus';

import { getMenuTreeApi } from '#/api/system/menu';
import { addRoleMenuPermissionsApi, type RoleMenuAssociationParams } from '#/api/system/role';

interface MenuItem {
  id: number;
  title: string;
  children?: MenuItem[];
}

interface Props {
  visible: boolean;
  roleId: number;
  roleName: string;
}

interface Emits {
  (e: 'update:visible', value: boolean): void;
  (e: 'submit'): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value),
});

const loading = ref(false);
const submitLoading = ref(false);
const treeRef = ref<InstanceType<typeof ElTree>>();
const menuTree = ref<MenuItem[]>([]);
const selectedMenuIds = ref<number[]>([]);
const selectedCount = ref(0);

const treeProps = {
  children: 'children',
  label: 'title',
};

// 获取菜单树
const getMenuTree = async () => {
  try {
    loading.value = true;
    const data = await getMenuTreeApi();
    menuTree.value = transformMenuData(data);
  } catch (error) {
    console.error('获取菜单列表失败:', error);
    ElMessage.error('获取菜单列表失败');
  } finally {
    loading.value = false;
  }
};

// 转换菜单数据格式
const transformMenuData = (menus: any[]): MenuItem[] => {
  return menus.map(menu => ({
    id: menu.id,
    title: menu.menuName || menu.name || menu.title || '',
    children: menu.children ? transformMenuData(menu.children) : undefined,
  }));
};

// 处理树节点选择
const handleCheck = () => {
  if (!treeRef.value) return;
  
  const checkedNodes = treeRef.value.getCheckedNodes();
  const halfCheckedNodes = treeRef.value.getHalfCheckedNodes();
  
  selectedCount.value = checkedNodes.length + halfCheckedNodes.length;
};

// 监听弹窗显示状态
watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      getMenuTree();
      selectedMenuIds.value = [];
      selectedCount.value = 0;
    }
  }
);

// 提交权限关联
const handleSubmit = async () => {
  if (!treeRef.value || !props.roleId) return;
  
  try {
    submitLoading.value = true;
    
    const checkedNodes = treeRef.value.getCheckedNodes();
    const halfCheckedNodes = treeRef.value.getHalfCheckedNodes();
    
    const allCheckedIds = [
      ...checkedNodes.map((node: any) => node.id),
      ...halfCheckedNodes.map((node: any) => node.id),
    ];
    
    if (allCheckedIds.length === 0) {
      ElMessage.warning('请至少选择一个权限');
      return;
    }
    
    // 使用新的角色权限关联API
    const params: RoleMenuAssociationParams = {
      roleId: props.roleId,
      menuIds: allCheckedIds,
    };
    
    await addRoleMenuPermissionsApi(params);
    
    ElMessage.success('权限关联成功');
    emit('submit');
    handleClose();
  } catch (error) {
    console.error('权限关联失败:', error);
    ElMessage.error('权限关联失败');
  } finally {
    submitLoading.value = false;
  }
};

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false;
  menuTree.value = [];
  selectedMenuIds.value = [];
  selectedCount.value = 0;
};
</script>

<style scoped>
.permission-content {
  max-height: 500px;
  overflow-y: auto;
}

.role-info {
  margin-bottom: 20px;
  text-align: center;
}

.permission-list h4 {
  margin: 10px 0;
  color: #333;
  font-size: 14px;
}

.menu-tree {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  margin-top: 10px;
}

.selected-count {
  margin-top: 15px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  text-align: center;
  color: #606266;
  font-size: 13px;
}

.dialog-footer {
  text-align: right;
}
</style> 
